package com.itheima.mynetty;

import com.itheima.mynetty.codec.ProtoStuffDecoder;
import com.itheima.mynetty.handler.server.ServerInboundHandler1;
import com.itheima.mynetty.handler.server.ServerReadIdleCheckHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServer {

    public static void main(String[] args) {
        NettyServer server = new NettyServer();
        server.start();
    }

    private void start() {
        //创建线程池
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //内置的\n换行符分隔
//                        pipeline.addLast(new LineBasedFrameDecoder(65535));
                        //内置的指定换行符分隔 我这里选用$分隔
//                        byte[] bytes = "$".getBytes(StandardCharsets.UTF_8);
//                        pipeline.addLast(new DelimiterBasedFrameDecoder(65535, pipeline.channel().alloc().buffer().writeBytes(bytes)));

                        //心跳检测
                        pipeline.addLast(new ServerReadIdleCheckHandler());
                        //固定长度字段存储数据长度
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                        //String序列化
//                        pipeline.addLast(new StringDecoder(StandardCharsets.UTF_8));

                        //protobuf序列化
//                        pipeline.addLast(new ProtobufDecoder(MessageProto.Message.getDefaultInstance()));
                        //protostuff序列化
                        pipeline.addLast(new ProtoStuffDecoder());
                        pipeline.addLast(new ServerInboundHandler1());
                    }
                });
        try {
            ChannelFuture future = bootstrap.bind(8888).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
